<template>
  <div class="app-container">
    <el-tooltip placement="top">
      <div slot="content">菜单功能需要与前台配置的Router匹配，请谨慎配置。最好配合代码自动生成功能使用。
        <br>菜单路径需要在前台router中预先定义。
        <br>菜单控制码对应后台Controller的名字。
        <br>菜单图表对应前台src/icons/svg目录下的图标名。
      </div>
      <el-button>配置说明</el-button>
    </el-tooltip>
    <div class="filter-container">
      <el-form ref="searchForm" :model="searchForm" :inline="true" @keyup.enter.native="search()">
        <el-form-item prop="menuId">
          <el-input v-model="searchForm.menuId" type="text" placeholder="菜单编号" maxlength="10" clearable />
        </el-form-item>
        <el-form-item prop="menuPath">
          <el-input v-model="searchForm.menuName" type="text" placeholder="菜单名" maxlength="10" clearable />
        </el-form-item>
        <el-form-item prop="menuPath">
          <el-input v-model="searchForm.menuPath" type="text" placeholder="菜单路径" maxlength="10" clearable />
        </el-form-item>
        <el-form-item prop="parentId">
          <el-input v-model="searchForm.parentId" type="text" placeholder="父菜单编号" maxlength="20" clearable />
        </el-form-item>
        <el-row>
          <el-col :span="14" />
          <el-col :span="10">
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="search()">查询</el-button>
              <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
                新增
              </el-button>
              <el-button @click="resetForm('searchForm')">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table
      v-loading="dataListLoading"
      element-loading-text="拼命加载中"
      size="mini"
      border
      :data="dataList"
      max-height="500"
      :row-class-name="tableRowClassName"
      style="width:100%"
    >
      <el-table-column
        prop="menuId"
        header-align="center"
        sortable
        align="center"
        label="菜单ID"
      />
      <el-table-column
        prop="menuName"
        header-align="center"
        align="center"
        label="菜单名"
      />
      <el-table-column
        prop="menuPath"
        header-align="center"
        align="center"
        label="菜单路径"
      />
      <el-table-column
        prop="controllerCode"
        header-align="center"
        align="center"
        label="后台控制码"
      />
      <el-table-column
        prop="parentId"
        header-align="center"
        align="center"
        label="父菜单ID"
        sortable
      />
      <el-table-column
        prop="menuType"
        header-align="center"
        align="center"
        label="菜单类型"
      >
        <template slot-scope="scope">
          <el-tag v-if="scope.row.menuType === '1'" size="mini" effect="dark">菜单</el-tag>
          <el-tag v-if="scope.row.menuType === '2'" size="mini" type="success" effect="dark">页面</el-tag>
          <el-tag v-if="scope.row.menuType === '3'" size="mini" type="info" effect="dark">页面控件</el-tag>
          <el-tag v-if="scope.row.menuId.length < 3" size="mini" type="warning" effect="dark">系统管理功能</el-tag>
          <el-tag v-if="scope.row.menuId.length > 3" size="mini" type="error" effect="dark">自动生成功能</el-tag>
        </template>
      </el-table-column>
      <el-table-column
        prop="menuLevel"
        header-align="center"
        align="center"
        label="菜单层次"
      />
      <el-table-column
        header-align="center"
        align="center"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleView(scope.row)">查看</el-button>
          <el-button v-if="scope.row.menuId.length > 3" type="text" size="small" @click="handleEdit(scope.row)">修改</el-button>
          <el-button v-if="scope.row.menuId.length > 3" type="text" size="small" @click="handleAddChild(scope.row)">修改</el-button>
        </template>
      </el-table-column></el-table>
    <!-- <Pagination v-show="total>0" :total="total" :page.sync="searchForm.page" :limit.sync="searchForm.limit" @pagination="search" /> -->

    <el-dialog v-el-drag-dialog :title="titleMap[dialogStatus]" :visible.sync="dialogVisible" center @dragDialog="handleDrag">
      <el-form ref="dataForm" :model="tempData" :rules="dataFormRules" :disabled="dialogStatus === 'view'" label-position="left" label-width="70px">
        <el-form-item label="菜单ID" prop="menuId">
          <el-input v-model="tempData.menuId" type="text" placeholder="菜单ID" maxlength="10" readonly />
        </el-form-item>
        <el-form-item label="菜单名" prop="menuName">
          <el-input v-model="tempData.menuName" type="text" placeholder="菜单名" maxlength="10" />
        </el-form-item>
        <el-form-item label="菜单路径" prop="menuPath">
          <el-input v-model="tempData.menuPath" type="text" placeholder="菜单路径" maxlength="20" />
        </el-form-item>
        <el-form-item label="后台功能码" prop="controllerCode">
          <el-input v-model="tempData.controllerCode" type="text" placeholder="后台功能码" maxlength="20" />
        </el-form-item>
        <el-form-item label="父菜单ID" prop="parentId">
          <el-input v-model="tempData.parentId" type="text" placeholder="父菜单ID" maxlength="20" />
        </el-form-item>
        <el-form-item label="菜单类型" prop="menuType">
          <!-- <el-input v-model="tempData.menuType" type="text" placeholder="父菜单ID" maxlength="20" /> -->
          <el-select v-model="tempData.menuType" placeholder="菜单类型">
            <el-option key="1" label="菜单" value="1" />
            <el-option key="2" label="页面" value="2" />
            <el-option key="3" label="页面控件" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单级别" prop="menuLevel">
          <el-input-number v-model="tempData.menuLevel" :min="1" :max="10" label="菜单级别" />
        </el-form-item>
        <el-form-item label="菜单图标" prop="menuIcon">
          <el-select v-model="tempData.menuIcon" filterable>
            <el-option label="user2" value="user2" />
            <el-option label="dashboard" value="dashboard" />
            <el-option label="example" value="example" />
            <el-option label="form" value="form" />
            <el-option label="link" value="link" />
            <el-option label="manage" value="manage" />
            <el-option label="report" value="report" />
            <el-option label="table" value="table" />
            <el-option label="user" value="user" />
            <el-option label="watcher" value="watcher" />
            <el-option label="watcher1" value="watcher1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-show="dialogStatus === 'update'" type="primary" @click="confirmUpdate">确 定</el-button>
        <el-button v-show="dialogStatus === 'update'" type="primary" @click="confirmDelete">删 除</el-button>
        <el-button v-show="dialogStatus === 'create'" type="primary" @click="confirmCreate">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
import { fetchData, upsertMenu, deleteData } from '@/api/menu'
import { Message } from 'element-ui'

export default {
  directives: { elDragDialog }, // dialog拖拽
  data() {
    return {
      dataListLoading: false, // 查询时数据加载中
      dataList: [], // 查询结果
      total: 0, // 查询总条数
      searchForm: {// 查询条件，查询表头+分页查询条件
        // page: 1,
        // limit: 20,
        // sort: '', 三个分页属性
        menuId: '',
        menuName: '',
        menuPath: '',
        controllerCode: '',
        parentId: '',
        menuType: '', // 生日查询范围
        menuLevel: ''
      },
      dialogVisible: false, // 数据窗口是否打开
      tempData: {// 新增或者修改的数据
        menuId: undefined,
        menuName: '',
        menuPath: '',
        controllerCode: '',
        parentId: '',
        menuType: '',
        menuLevel: '',
        menuIcon: ''
      },
      dialogStatus: '', // 数据框状态-修改、新增
      titleMap: {// 数据框标题
        view: '查看数据',
        update: '修改数据',
        create: '新增数据'
      },
      dataFormRules: {// 添加数据时的检查规则
        menuName: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 64, message: '超过最大长度', trigger: 'blur' }
        ],
        menuPath: [
          { max: 64, message: '超过最大长度', trigger: 'blur' }
        ],
        controllerCode: [
          { max: 64, message: '超过最大长度', trigger: 'blur' }
        ],
        parentId: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 32, message: '超过最大长度', trigger: 'blur' }
        ],
        menuType: [
          { required: true, message: '必填数据', trigger: 'change' },
          { max: 2, message: '超过最大长度', trigger: 'blur' }
        ],
        menuLevel: [
          { required: true, message: '必填数据', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.search()
  },
  methods: {
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    search() { // 查询数据方法
      this.dataListLoading = true
      fetchData(this.searchForm).then(response => {
        this.dataList = response
        this.dataListLoading = false
      })
    },
    resetTemp() {
      this.tempData = {
        id: undefined,
        name: '',
        remark: '',
        salary: '',
        birthday: '',
        createtime: ''
      }
    },
    handleCreate() { // 点击新增按钮方法
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmCreate() { // 创建数据方法
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$confirm('确认添加数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            upsertMenu(this.tempData).then(response => {
              this.dialogVisible = false
              Message.success('数据新增成功')
              this.search()
            })
          }).catch(() => {
            console.info('已取消')
          })
        }
      })
    },
    handleEdit(row) { // 点击修改数据
      this.tempData = Object.assign({}, row) // 复制对象，不进行双向绑定。
      this.dialogStatus = 'update'
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleAddChild(row) { // 点击添加子菜单
      this.tempData = {}
      this.tempData.parentId = row.parentId
      this.dialogStatus = 'update'
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmUpdate() { // 修改数据方法
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$confirm('确认修改数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'info'
          }).then(() => {
            upsertMenu(this.tempData).then(response => {
              if (response === -2) {
                Message.error('后台控制码或者菜单Code重复')
              } else if (response === -1) {
                Message.error('菜单添加失败')
              } else {
                Message.success('数据修改成功')
                this.dialogVisible = false
                this.search()
              }
            })
          }).catch(() => {
            console.info('已取消')
          })
        }
      })
    },
    confirmDelete() { // 修改数据方法 ID主键设为readonly，删除时就不需要校验了。
      if (this.tempData.menuId.length < 10) {
        this.$message.error('系统预设菜单不能删除。')
        return false
      }
      this.$confirm('确认修改数据', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }).then(() => {
        deleteData(this.tempData).then(response => {
          Message.success('数据修改成功')
          this.dialogVisible = false
          this.search()
        })
      }).catch(() => {
        console.info('已取消')
      })
    },
    handleView(row) { // 点击查看数据
      this.tempData = Object.assign({}, row) // 复制对象，不进行双向绑定。
      this.dialogStatus = 'view'
      this.dialogVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleDrag() { // dialog拖拽事件
    },
    tableRowClassName({ row, rowIndex }) {
      if (row.menuType === '1') {
        return 'warning-row'
      } else if (row.menuType === '2') {
        return 'success-row'
      } else if (row.menuType === '3') {
        return 'info-row'
      } else {
        return ''
      }
    }
  }
}
</script>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }

  .el-table .info-row {
    background: azure;
  }
</style>
